import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.border.TitledBorder;

public class ControlPanel extends JPanel{

	private final int X_DIMENSION = 1200, Y_DIMENSION = 150;
	private static JLabel redScore, blueScore, redMarker, blueMarker;
	private static  JTextArea output, stopwatch;
	private JPanel scorePanel, outputPanel, controls, timePanel;
	private JFrame help;
	private static ArrayList<String> outputList;
	private JButton exit, startPause;
	private boolean paused = true, started = false;
	private JScrollPane outputScroll;
	public static int counter=0;
	public static StringBuilder outputStrings = new StringBuilder();
	private Color stopwatchColor;
	public static Time userTime;
	public static Timer stopwatchTimer;
	public static int time = 12000;

	public ControlPanel(){

		setFocusable(true);
		addKeyListener(new HelpMenuListener());
		setBackground(Color.LIGHT_GRAY);
		setPreferredSize(new Dimension(X_DIMENSION,Y_DIMENSION));
		setLayout(new GridLayout(1, 4));

		help = new JFrame();

		outputList = new ArrayList<String>();

		redScore = new JLabel("0");
		blueScore = new JLabel("0");
		redMarker = new JLabel("Red Alliance Score");
		redMarker.setBackground(Color.red);
		redMarker.setForeground(Color.red);
		blueMarker = new JLabel("Blue Alliance Score");
		blueMarker.setBackground(Color.blue);
		blueMarker.setForeground(Color.blue);

		scorePanel = new JPanel();
		scorePanel.setLayout(new GridLayout(2,2));

		outputPanel = new JPanel();
		outputPanel.setLayout(null);

		timePanel = new JPanel();
		timePanel.setLayout(null);

		userTime = new Time(time);
		stopwatchTimer = new Timer(1000, new TimeListener());

		//The stop watch is initially set to represent 2 minutes (the starting time)
		stopwatch = new JTextArea();
		stopwatch.setText("02 : 00");
		stopwatch.setForeground(Color.BLACK);
		stopwatch.setEditable(false);
		stopwatch.setFont(new Font("Courier New", Font.BOLD, 30));
		stopwatch.setOpaque(false);
		stopwatch.setBounds(80, 50, 250, 50);
		timePanel.add(stopwatch);
		timePanel.setBackground(Color.LIGHT_GRAY);

		scorePanel.add(redMarker);
		scorePanel.add(blueMarker);
		scorePanel.add(redScore);
		scorePanel.add(blueScore);

		//Output console added to a scroll pane
		output = new JTextArea("Output Console:");
		output.setLineWrap(true);
		output.setColumns(1);

		outputScroll = new JScrollPane(output);
		outputScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		outputPanel.add(outputScroll);
		outputPanel.setLayout(new GridLayout(1,1));

		exit = new JButton("Exit");
		exit.addActionListener(new ControlsListener());
		startPause = new JButton("Start");
		startPause.addActionListener(new ControlsListener());

		controls = new JPanel();
		controls.setLayout(new GridLayout(3,1));
		controls.add(exit);
		controls.add(startPause);

		//Titled borders		
		TitledBorder tb = BorderFactory.createTitledBorder("Score Panel");
		tb.setTitleJustification(TitledBorder.LEFT);
		scorePanel.setBorder(tb);

		TitledBorder tb2 = BorderFactory.createTitledBorder("Output Console");
		tb2.setTitleJustification(TitledBorder.LEFT);
		outputPanel.setBorder(tb2);

		TitledBorder tb3 = BorderFactory.createTitledBorder("Controls");
		tb3.setTitleJustification(TitledBorder.LEFT);
		controls.setBorder(tb3);

		TitledBorder tb4 = BorderFactory.createTitledBorder("Stopwatch");
		tb4.setTitleJustification(TitledBorder.LEFT);
		timePanel.setBorder(tb4);

		add(outputPanel);
		add(scorePanel);
		add(controls);
		add(timePanel);
	}

	public static void output(String string){

		//Adds strings to a string builder, which forms a log of robot activity
		//that can be accessed (statically) anywhere in the program
		outputList.add(string);

		//Prints the title only if this is the first time through
		if(counter==0){
			outputStrings.append("Output Console:\n");
		}
		for(int i=counter; i<outputList.size(); i++){
			outputStrings.append("--" + outputList.get(i));
			outputStrings.append("\n");
		}

		output.setText(outputStrings.toString());
		counter++;
	}

	//Updates the score from anywhere in the program (statically)
	public static void updateBlueScore(int addition){
		RoboticsProjectPanel.bluePoints += addition;
		blueScore.setText(Integer.toString(RoboticsProjectPanel.bluePoints));
	}

	public static void updateRedScore(int addition){
		RoboticsProjectPanel.redPoints += addition;
		redScore.setText(Integer.toString(RoboticsProjectPanel.redPoints));
	}

	//Allows the user to access the help menu by pressing the h key
	private class HelpMenuListener implements KeyListener {

		public void keyPressed(KeyEvent event) {
			if (event.getKeyCode() == KeyEvent.VK_H){
				help.setVisible(true);
			}

			if (event.getKeyCode() == KeyEvent.VK_ESCAPE){
				help.setVisible(false);
			}
		}

		//Overridden methods
		public void keyReleased(KeyEvent event) {}
		public void keyTyped(KeyEvent event) {}

	}

	private class ControlsListener implements ActionListener {

		public void actionPerformed(ActionEvent button) {

			//Exit case
			if (button.getSource().equals(exit)) {
				RoboticsProjectPanel.repainter.stop();
				System.exit(0);
			}

			//Start/Pause case
			if (button.getSource().equals(startPause)) {

				if (paused) {
					//When not started, start all threads, timers, etc.
					if(!started){
						started = true;

						for(int i=0; i<3; i++){
							RoboticsProjectPanel.robotList[0][i].start();
							output("Blue robot " + i + " has been started!");
							RoboticsProjectPanel.robotList[1][i].start();
							output("Red robot " + i + " has been started!");
							stopwatchTimer.start();
						}
					}
					//Otherwise, just start the timers
					startPause.setText("Pause");
					paused = false;
					RoboticsProjectPanel.repainter.start();
					stopwatchTimer.start();					
				}

				//If not paused, stop timers and pause thread
				else {
					startPause.setText("Continue");
					paused = true;
					RoboticsProjectPanel.repainter.stop();
					stopwatchTimer.stop();					
				}
			}
		}
	}

	//Handles the stop watch
	private class TimeListener implements ActionListener
	{
		public void actionPerformed(ActionEvent event){
			time-=100;
			userTime.setTime(time);
			stopwatch.setText(userTime.timeToString());
			stopwatch.setForeground(stopwatchColor);

			//When there is no time left, display a message saying who wins and the final score
			if(time==0){
				stopwatchTimer.stop();
				RoboticsProjectPanel.repainter.stop();
				String winner;
				int greater=0;
				int lesser=0;
				if(RoboticsProjectPanel.redPoints > RoboticsProjectPanel.bluePoints){
					winner = "Red";
					greater = RoboticsProjectPanel.redPoints;
					lesser = RoboticsProjectPanel.bluePoints;
				}
				else if(RoboticsProjectPanel.bluePoints > RoboticsProjectPanel.redPoints){
					winner = "Blue";
					greater = RoboticsProjectPanel.bluePoints;
					lesser = RoboticsProjectPanel.redPoints;
				}
				else{
					winner = "Tie";
				}

				JOptionPane.showMessageDialog(null, "The winner is: " + winner + " \n\tby a score of: " + greater + "-" + lesser, 
						"Game Over!", JOptionPane.INFORMATION_MESSAGE);
			}
		}
	}
}